#!/usr/bin/python
import random
import cgi, cgitb
import MySQLdb
import os
from config import *
import sha


form = cgi.FieldStorage()
configure = config()
def headerPrint():
    print '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /><title>Original ~ Shorten those long urls</title><link rel="stylesheet" href="styles.css" type="text/css" /></head><body><div id="wrap">	<div class="header">		<div class="title">			<h1><a href="http://origin.al.eu.org">Original</a></h1>			<h2>Python URL Shortening Service</h2>		</div>		<div class="nav">			<ul>				<li><a href="index.html">Home</a></li>			</ul>		</div>		<div class="clear"></div>	</div>	<div class="pagewrapper">		<div class="innerpagewrapper">			<div class="page">				<div class="content">					<p>'

def footerPrint():
    print '</p>				</div>				<div class="footer">					<p>&copy;&nbsp;2010&nbsp;<a href="http://origin.al.eu.org">Origin.al.eu.org</a>|Design: <a href="http://www.spyka.net">spyka webmaster</a></p> 				</div>			</div>		</div>	</div></div></body></html>'


ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
def base62_encode(num, alphabet=ALPHABET):
    """Encode a number in Base X

    `num`: The number to encode
    `alphabet`: The alphabet to use for encoding
    """
    if (num <= 0):
        return alphabet[0]
    arr = []
    base = len(alphabet)
    while num:
        rem = num % base
        num = num // base
        arr.append(alphabet[rem])
    arr.reverse()
    return ''.join(arr)
url = form.getvalue('url')
if(url==None):
    print 'Content-type: text/html\n\n'
    headerPrint()
    print "<h2><font color='red'>Access Denied</font></h2>"
    footerPrint()
    exit()
check = url[:4]
if(check!="http"):
    url = "http://"+url
print 'Content-type: text/html\n\n'
headerPrint()
print "<h2><font color='black'>"+url+" shortened to : "
data = ""
valRange = ""
for i in range(5):
    val = random.randint(0,62)
    valRange = valRange + str(val)
    data = data + base62_encode(val)
ip = cgi.escape(os.environ["REMOTE_ADDR"])
try:
    db = MySQLdb.connect(host=configure.dbHostname,user=configure.dbUsername,passwd=configure.dbPassword,db=configure.dbName)
    sql = """insert into link_database(hash,link,ipaddress) values(%s,'%s','%s')""" %(valRange,url,ip)
    db.query(sql)
    result = db.store_result()
except MySQLdb.Error, e:
     print "Error %d: %s" % (e.args[0], e.args[1])
#print result
print "<a href='"+configure.url+data+"'>"+configure.url+data+"</a></font></h2><br />"
print "Your ip has been recorded: "+ip
footerPrint()